<script setup lang="ts">
import { onMounted, onBeforeUnmount, onUpdated } from "vue";
import { VChart, IChart, ILineChartSpec } from "@visactor/vchart";

interface ChartProps {
  colors?: string[];
}

const props = defineProps<ChartProps>();

let chart: IChart;

const spec = {
  type: 'pie',
  data: [
    {
      id: 'id0',
      values: [
        { type: 'oxygen', value: '46.60' },
        { type: 'silicon', value: '27.72' },
        { type: 'aluminum', value: '8.13' },
        { type: 'iron', value: '5' },
        { type: 'calcium', value: '3.63' },
        { type: 'sodium', value: '2.83' },
        { type: 'potassium', value: '2.59' },
        { type: 'others', value: '3.5' }
      ]
    }
  ],
  outerRadius: 0.8,
  valueField: 'value',
  categoryField: 'type',
  title: {
    visible: true,
    text: 'Statistics of Surface Element Content'
  },
  legends: {
    visible: true,
    orient: 'bottom'
  },
  label: {
    visible: true
  },
  tooltip: {
    mark: {
      content: [
        {
          key: datum => datum['type'],
          value: datum => datum['value'] + '%'
        }
      ]
    }
  }
};

function createOrUpdateChart(chartProps: ChartProps) {
  const container = document.getElementById("chart-container");
  if (container && !chart) {
    chart = new VChart(spec, {
      dom: container,
    });

    chart.renderAsync();
    return true;
  } else if (chart) {
    chart.updateSpec(spec);
    chart.renderAsync();

    return true;
  }
  return false;
}

onMounted(() => {
  createOrUpdateChart(props);
});

onUpdated(() => {
  createOrUpdateChart(props);
});

onBeforeUnmount(() => {
  if (chart) {
    chart.release();
  }
});
</script>

<template>
  <div class="chart-container" id="chart-container"></div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
}
</style>
